package com.notecalendar.dao.impl;

import java.math.BigInteger;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.notecalendar.dao.Evernote_LoginDao;
import com.notecalendar.model.Evernote_Login;

/**
 * Class for implementing the methods definite in Evernote_LoginDao
 * @author bcamcereijo
 *
 */
public class Evernote_LoginDaoImpl extends HibernateDaoSupport implements Evernote_LoginDao{
	
	/**
	 * @see Evernote_LoginDao#deleteEvernoteLogin(Evernote_Login)
	 */
	public void deleteEvernoteLogin(Evernote_Login evernoteLogin) {
		getHibernateTemplate().delete(evernoteLogin);
	}
	
	/**
	 * @see Evernote_LoginDao#insertEvernote_Login(Evernote_Login)
	 */
	public Evernote_Login insertEvernote_Login(Evernote_Login evernoteLogin) {
		evernoteLogin.setId(getNotesMaxId());
			
		SQLQuery tempQuery = getSession().createSQLQuery(
				"INSERT INTO EVERNOTE_LOGIN  (id,evernote_user,evernote_pass) "+
				"VALUES (?,AES_ENCRYPT(?, 'notecalendar_secret_key'),AES_ENCRYPT(?, 'notecalendar_secret_key'))");
		tempQuery.setBigInteger(0, evernoteLogin.getId());
		tempQuery.setString(1, evernoteLogin.getEvernote_user());
		tempQuery.setString(2, evernoteLogin.getEvernote_pass());
		tempQuery.executeUpdate();
		
		return evernoteLogin;
	}

	/**
	 * @see Evernote_LoginDao#selectEvernote_Login(int)
	 */
	@SuppressWarnings("unchecked")
	public Evernote_Login selectEvernote_Login(BigInteger id) {
		
		Query query = getSession().getNamedQuery("getEvernote_loginById");
		query.setBigInteger(0, id);
		List<Evernote_Login> lista = (List<Evernote_Login>)query.list();
		
		return lista.size()>0?lista.get(0):null;
	}
	
	/**
	 * Get the max id  from evernote_login table 
	 * @return
	 */
	private BigInteger getNotesMaxId(){
		Query query = getSession().getNamedQuery("evernote_loginMaxId");
		
		BigInteger id = (BigInteger)query.list().get(0);
		id = (id==null)?new BigInteger("0"):id;

		return id;
	}
}
